package com.codermn.并发访问控制.synchronize案例;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author jxau_scf
 * @date 2021/8/31 - 10:46
 */
public class SynchronizeDemo {
    private int o = 0;
    AtomicInteger atomicInteger = new AtomicInteger();

    //synchoronized修饰非静态方法
    public synchronized void function() throws InterruptedException {
        for (int i = 0; i < 3; i++){
            o++;
            Thread.sleep(1000);
            System.out.println("function running... i: " + o);
        }
    }

    //synchronize修饰静态方法
    public static synchronized void staticFunction() throws InterruptedException {
        for (int i = 0; i < 3; i++){
            Thread.sleep(1000);
            System.out.println("static function running...");
        }
    }

    public static void main(String[] args) {
        final SynchronizeDemo synchronizeDemo = new SynchronizeDemo();
        Thread thread1 = new Thread(() -> {
            try {
                synchronizeDemo.function();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread thread2 = new Thread(() -> {
            try {
                synchronizeDemo.function();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        //启动
        thread1.start();
        thread2.start();
    }
}
